package br.unifor.g2cl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public abstract class Util {

	public static Object getObjectFromByte(byte[] arr, int offset, int length) throws Exception {
		Object returnVal = null;
		ObjectInputStream in;
		in = new ObjectInputStream(new ByteArrayInputStream(arr, offset, length));
		returnVal = in.readObject();
		in.close();
		return returnVal;
	}

	public static byte[] getArrayFromObject(Object o) throws Exception {
		byte[] object = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(bos);
		out.writeObject(o);
		out.close();
		object = bos.toByteArray();
		return object;
	}

	public static byte[] intToByteArray(int data) {
		byte[] dataArray = new byte[4];
		dataArray[0] = (byte) (0xFF & data);
		dataArray[1] = (byte) (0xFF & (data >> 8));
		dataArray[2] = (byte) (0xFF & (data >> 16));
		dataArray[3] = (byte) (0xFF & (data >> 24));
		return dataArray;
	}
	
	public static void intToByteArray(byte[] array, int offset, int value) {
		array[offset] = (byte) (0xFF & value);
		array[offset+1] = (byte) (0xFF & (value >> 8));
		array[offset+2] = (byte) (0xFF & (value >> 16));
		array[offset+3] = (byte) (0xFF & (value >> 24));
	}
	

	public static int byteArrayToInt(byte[] data) {
		return 	((int) data[0] & 0xFF) | 
				(((int) data[1] & 0xFF) << 8) |
				(((int) data[2] & 0xFF) << 16) |
				(((int) data[3] & 0xFF) << 24);
	}
	
	public static int byteArrayToInt(byte[] data, int offset) {
		return 	((int) data[offset] & 0xFF) | 
				(((int) data[offset+1] & 0xFF) << 8) |
				(((int) data[offset+2] & 0xFF) << 16) |
				(((int) data[offset+3] & 0xFF) << 24);
	}
}
